package com.iuie.ns.devtools.transfer;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.iuie.ns.devtools.to.DevBodyTO;
import com.iuie.ns.devtools.to.DevHeaderTO;
import com.iuie.ns.frame.utils.ListUtils;
import com.iuie.ns.frame.utils.StringTemplateUtils;
import com.iuie.ns.frame.utils.StringUtils;
import com.iuie.ns.system.vo.code.SysCodeInfoVO;

@Component("tableCreateMySQLTransfer")
public class TableCreateMySQLDevTransfer extends BaseDevTransfer {

	@Override
	public String transfer(List<? extends DevBodyTO> list, DevHeaderTO header) {
		
		StringBuilder sb = new StringBuilder(12);
		if (ListUtils.isNotEmpty(list)) {
			StringBuilder primaryKeyBuilder = new StringBuilder(12); // 主键，兼容联合主键
			for (int i = 0; i < list.size(); i++) {
				// 拼接字段
				DevBodyTO body = list.get(i);
				String field = body.getMySQLFieldElement().build();
				sb.append(field);
				
				// 组合联合主键
				if (body.isIdAttribute()) {
					primaryKeyBuilder.append(body.getFieldName())
						.append(", ");
				}
				
				if (i != (list.size() - 1)) {
					continue;
				}
				
				if (primaryKeyBuilder.length() > 2) {
					String strPrimaryKey = primaryKeyBuilder.delete(primaryKeyBuilder.length() - 2, primaryKeyBuilder.length()).toString();
					if (StringUtils.isNotBlank(strPrimaryKey)) {
						sb.append("\tprimary key(")
						.append(strPrimaryKey)
						.append(")");
					}
				} else {
					// 删除最后一个的逗号和回车
					sb.delete(sb.length() - 2, sb.length());
				}
			}
		}
		
		String tableName = header.getTableName();
		String db = header.getDb();
		
		if (StringUtils.isBlank(db)) {
			db = "mysql";
		}
		
		// 获取sql模板
		SysCodeInfoVO sqlCode = sysCodeService.findCodeInfoByCodeValueAndCodeType(db + "_tableCreate", "sqlTemplate");
		String sqlTemplate = sqlCode.getCodeInfoName(); // SQL模板
		
		// 构造模板的参数
		Map<String, String> data = new HashMap<String, String>();
		data.put("tableName", tableName);
		data.put("fields", sb.toString());
		
		// 给sql模板赋值，获取SQL
		String s = StringTemplateUtils.render(sqlTemplate, data);
		return s;
	}

}
